from django.contrib.auth.models import Permission, Group
from rest_framework import serializers
from apps.users.models import User
# 用户权限序列化器
class PermissionSerialzier(serializers.ModelSerializer):
    class Meta:
        model = Permission
        fields = "__all__"
# 用户组序列化器
class GroupSerialzier(serializers.ModelSerializer):
    class Meta:
        model = Group
        fields = "__all__"


class AdminSerialzier(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = "__all__"
        read_only_fields = ["id"]
        extra_kwargs = {
            'password': {
                'write_only': True
            }
        }
    def create(self, validated_data):
    # ===================未实现  管理员权限添加不上
        # 添加管理员字段
        validated_data["is_staff"] = True
        # 调用父类方法创建管理员用户
        admin = super().create(validated_data)
        # 用户加密
        password = validated_data['password']
        admin.set_password(password)
        admin.save()
        return admin
    def update(self,instance,validated_data):
        # 添加管理员字段
        validated_data['is_staff'] = True
        # 调用父类方法创建管理员用户
        admin = super().update(instance, validated_data)
        # 用户密码加密
        password = validated_data['password']
        admin.set_password(password)
        admin.save()
        return admin


class GroupSimpleSerializers(serializers.ModelSerializer):
    class Meta:
        model = Group
        fields = ["id","name"]
